#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
批量处理视频文件，在视频上添加指定文本
"""

import os
import sys
import random
import subprocess
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.append(str(project_root))

from src.processors.video_text_overlay import add_text_to_video


def get_audio_duration(audio_path):
    """
    获取音频文件的时长(秒)
    """
    # 确保路径是字符串格式
    audio_path_str = str(audio_path)
    
    cmd = [
        'ffprobe', '-v', 'error', '-show_entries', 'format=duration',
        '-of', 'default=noprint_wrappers=1:nokey=1', audio_path_str
    ]
    
    try:
        result = subprocess.run(
            cmd, 
            stdout=subprocess.PIPE, 
            stderr=subprocess.PIPE, 
            text=True, 
            timeout=30,
            encoding='utf-8',
            errors='replace'  # 替换无法解码的字符
        )
        duration = float(result.stdout.strip())
        return duration
    except Exception as e:
        print(f"获取音频时长失败 {audio_path}: {e}")
        return None


def extract_audio_from_video(video_path, audio_path, duration):
    """
    从视频中提取指定时长的音频
    """
    cmd = [
        'ffmpeg', '-y', '-i', str(video_path),
        '-t', str(duration), '-vn', '-acodec', 'copy', str(audio_path)
    ]
    
    try:
        result = subprocess.run(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            timeout=60,
            encoding='utf-8',
            errors='replace'
        )
        return result.returncode == 0
    except Exception as e:
        print(f"提取音频失败: {e}")
        return False


def merge_audio_video(video_path, audio_path, output_path):
    """
    将音频和视频合并
    """
    cmd = [
        'ffmpeg', '-y', '-i', str(video_path),
        '-i', str(audio_path), '-c:v', 'copy', '-c:a', 'aac', str(output_path)
    ]
    
    try:
        result = subprocess.run(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            timeout=60,
            encoding='utf-8',
            errors='replace'
        )
        return result.returncode == 0
    except Exception as e:
        print(f"合并音视频失败: {e}")
        return False


def add_bgm_to_videos(video_directory, audio_directory, output_directory):
    """
    为视频目录中的所有视频添加背景音乐
    
    Args:
        video_directory (str): 视频文件所在目录
        audio_directory (str): 音频文件所在目录
        output_directory (str): 输出视频文件目录
    """
    # 支持的视频文件扩展名
    video_extensions = {'.mp4', '.avi', '.mov', '.mkv', '.flv', '.wmv', '.webm'}
    
    # 支持的音频文件扩展名
    audio_extensions = {'.mp3', '.wav', '.aac', '.flac', '.m4a', '.ogg'}
    
    # 确保输出目录存在
    os.makedirs(output_directory, exist_ok=True)
    
    # 获取目录中的所有视频文件
    video_files = []
    for file in os.listdir(video_directory):
        if Path(file).suffix.lower() in video_extensions:
            video_files.append(file)
    
    if not video_files:
        print(f"在目录 {video_directory} 中未找到视频文件")
        return False
    
    # 获取目录中的所有音频文件
    audio_files = []
    for file in os.listdir(audio_directory):
        if Path(file).suffix.lower() in audio_extensions:
            audio_files.append(file)
    
    if not audio_files:
        print(f"在目录 {audio_directory} 中未找到音频文件")
        return False
    
    print(f"找到 {len(video_files)} 个视频文件和 {len(audio_files)} 个音频文件")
    
    # 处理每个视频文件
    success_count = 0
    for i, video_file in enumerate(video_files, 1):
        input_video_path = os.path.join(video_directory, video_file)
        output_filename = f"{Path(video_file).stem}_with_bgm{Path(video_file).suffix}"
        output_path = os.path.join(output_directory, output_filename)
        
        print(f"\n[{i}/{len(video_files)}] 处理: {video_file}")
        
        # 随机选择一个音频文件
        selected_audio = random.choice(audio_files)
        input_audio_path = os.path.join(audio_directory, selected_audio)
        print(f"  选择音频文件: {selected_audio}")
        
        # 获取视频时长
        video_duration = get_audio_duration(input_video_path)
        if not video_duration:
            print(f"  ❌ 无法获取视频时长: {video_file}")
            continue
        
        print(f"  视频时长: {video_duration:.2f} 秒")
        
        # 提取与视频时长相同的音频片段
        temp_audio = Path(output_path).with_suffix('.temp_audio.mp3')
        if not extract_audio_from_video(input_audio_path, temp_audio, video_duration):
            print(f"  ❌ 音频片段提取失败")
            if temp_audio.exists():
                temp_audio.unlink()
            continue
        
        print(f"  音频片段提取完成")
        
        # 合并音视频
        if merge_audio_video(input_video_path, temp_audio, output_path):
            print(f"  ✅ 成功生成: {output_filename}")
            success_count += 1
        else:
            print(f"  ❌ 音频视频合并失败: {video_file}")
        
        # 清理临时音频文件
        if temp_audio.exists():
            temp_audio.unlink()
    
    print(f"\n处理完成: {success_count}/{len(video_files)} 个视频成功添加背景音乐")
    return success_count > 0


def batch_process_videos(video_directory, output_directory, text_config_list):
    """
    批量处理视频目录中的所有视频文件
    
    Args:
        video_directory (str): 视频文件所在目录
        output_directory (str): 输出视频文件目录
        text_config_list (list): 文本配置列表的列表，每个视频使用一个文本配置
    """
    # 支持的视频文件扩展名
    video_extensions = {'.mp4', '.avi', '.mov', '.mkv', '.flv', '.wmv', '.webm'}
    
    # 确保输出目录存在
    os.makedirs(output_directory, exist_ok=True)
    
    # 获取目录中的所有视频文件
    video_files = []
    for file in os.listdir(video_directory):
        if Path(file).suffix.lower() in video_extensions:
            video_files.append(file)
    
    if not video_files:
        print(f"在目录 {video_directory} 中未找到视频文件")
        return False
    
    print(f"找到 {len(video_files)} 个视频文件")
    
    # 处理每个视频文件
    success_count = 0
    for i, video_file in enumerate(video_files, 1):
        input_path = os.path.join(video_directory, video_file)
        output_filename = f"{Path(video_file).stem}_with_text{Path(video_file).suffix}"
        output_path = os.path.join(output_directory, output_filename)
        
        print(f"\n[{i}/{len(video_files)}] 处理: {video_file}")
        
        # 选择对应的文本配置（循环使用）
        text_index = (i - 1) % len(text_config_list)
        current_text_config = text_config_list[text_index]
        
        print(f"  使用第 {text_index + 1} 个文案")
        
        # 检查输出文件是否已存在
        # if os.path.exists(output_path):
            # print(f"  输出文件已存在，跳过: {output_filename}")
            # continue
        
        # 处理视频
        try:
            success = add_text_to_video(input_path, output_path, current_text_config)
            if success:
                print(f"  ✅ 成功生成: {output_filename}")
                success_count += 1
            else:
                print(f"  ❌ 处理失败: {video_file}")
        except Exception as e:
            print(f"  ❌ 处理出错: {e}")
    
    print(f"\n文字添加完成: {success_count}/{len(video_files)} 个视频成功添加文字")
    return success_count > 0


def main():
    """主函数"""
    # 示例使用
    # 可以根据需要修改这些参数
    
    # 视频目录（可以修改为实际路径）
    video_dirs = [
        r"D:\Data\20251024",
        r".\videos"  # 默认本地视频目录
    ]
    
    # 查找存在的视频目录
    video_directory = None
    for directory in video_dirs:
        if os.path.exists(directory):
            video_directory = directory
            break
    
    if not video_directory:
        print("未找到视频目录，请确保以下目录之一存在:")
        for directory in video_dirs:
            print(f"  - {directory}")
        return
    
    # 输出目录
    output_directory = "./output/batch_processed"
    
    # 音频目录（用于添加背景音乐）
    audio_dirs = [
        r"D:\Data\music",  # 指定的音乐目录
        r"D:\Data\20251024\audios",
        r".\audios"  # 默认本地音频目录
    ]
    
    # 查找存在的音频目录
    audio_directory = None
    for directory in audio_dirs:
        if os.path.exists(directory):
            audio_directory = directory
            break
    
    text = [
"""
Entrou, ganhou um mimo especial!
Aprenda e acompanhe as análises dos especialistas!
Sorte e boas vibrações estão te esperando!
""",
"""
Participe e aproveite recompensas incríveis!
Quanto mais você interage, mais vantagens desbloqueia!
 Aqui, cada participação vale de verdade!
""",
"""
Vem participar e descobrir as surpresas que te esperam!
 Cada passo aqui vale a pena — quanto mais você joga, mais diversão vem junto!
 Aproveite cada momento e sinta a energia do futebol com a gente!
"""
    ]

    # 文本配置示例（巴西葡萄牙语）
    texts = [
        [{
            'text': text[0],
            'position': ('center', 'center'),
            'fontsize': 30,
            'color': 'yellow',
            'stroke_color': 'black',
            'stroke_width': 2,
            'duration': 10,
            'start_time': 0,
            'max_width': 1000,
            'add_shadow': True,
            'shadow_color': 'black',
            'shadow_offset': (3, 3),
            'video_duration': True  # 文本持续时间与视频相同
        }],
        [{
            'text': text[1],
            'position': ('center', 'center'),
            'fontsize': 30,
            'color': 'yellow',
            'stroke_color': 'black',
            'stroke_width': 2,
            'duration': 10,
            'start_time': 0,
            'max_width': 1000,
            'add_shadow': True,
            'shadow_color': 'black',
            'shadow_offset': (3, 3),
            'video_duration': True  # 文本持续时间与视频相同
        }],
        [{
            'text': text[2],
            'position': ('center', 'center'),
            'fontsize': 30,
            'color': 'yellow',
            'stroke_color': 'black',
            'stroke_width': 2,
            'duration': 10,
            'start_time': 0,
            'max_width': 1000,
            'add_shadow': True,
            'shadow_color': 'black',
            'shadow_offset': (3, 3),
            'video_duration': True  # 文本持续时间与视频相同
        }]
    ]
    
    print(f"视频目录: {video_directory}")
    print(f"输出目录: {output_directory}")
    print("开始批量处理视频...")
    
    # 第一步：先给视频添加文字
    text_output_directory = os.path.join(output_directory, "with_text")
    text_success = batch_process_videos(video_directory, text_output_directory, texts)
    
    # 第二步：如果添加背景音乐的目录存在，则给带文字的视频添加背景音乐
    if audio_directory and text_success:
        print(f"\n音频目录: {audio_directory}")
        bgm_output_directory = os.path.join(output_directory, "with_bgm")
        print("开始为带文字的视频添加背景音乐...")
        add_bgm_to_videos(text_output_directory, audio_directory, bgm_output_directory)
        print("背景音乐添加完成")
    elif not audio_directory:
        print("未找到音频目录，跳过背景音乐添加步骤")
    
    print("批量处理完成")


if __name__ == "__main__":
    main()